#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/stat.h>

#include "help/util.h"

// I have had a nasty problem here, which should be remembered when occuring once again
// Since the change from chroot to a root path, the 64 byte string were too small
// So memory was overwritten, which really shouldnt be

// For now, I made the strings 256 bytes big, but this is just a temp solution
// The best would be to determine the max path length and base the strings lengths on that
// Or create dynamic strings, which grow bigger when filled

int main(int argc, char* argv[]) {
    if (argc < 2) {
        return 1;
    }

    char* root = getenv("RELAT_ROOT");
    char* name = argv[1];

    if (strlen(name) < 3) {
        exit(-1);
    }

    // TODO: improve spawning position
    int user_count = get_user_count(); 
    printf("%i\n", user_count);
    float pos_x = 10 * user_count;
    float pos_y = 10 * user_count;
    float pos_z = 0;

    char name_dir[256];
    sprintf(name_dir, "%s/%s", root, name);
    if (mkdir(name_dir) != 0) {
        perror("mkdir failed");
        return 1;
    }

    char user_position_file_name[256];
    sprintf(user_position_file_name, "%s/%s/position", root, name);
    FILE* user_position_file;
    if ((user_position_file = fopen(user_position_file_name, "w")) == NULL) {
        perror("could not create user position file");
        return 1;
    }
    fprintf(user_position_file, "%.3f %.3f %.3f\n", pos_x, pos_y, pos_z);
    fclose(user_position_file);

    create_unit(name, "adam", 1, 0);
    create_unit(name, "eva", -1, 0);

    return 0;
}
